function addEcbItem(a, tlbId)
{
  var ecbTable = getEcbItemsOfById(tlbId);
  if(ecbTable != null)
  {
    ecbTable = ecbTable.childNodes[0]; // TBODY child 

    var row = document.createElement('tr');
    fillCells(row, a);
    ecbTable.appendChild(row);
  }
}

function fillCells(tr, a){
  for (i in a)
  {
    var td = document.createElement('td')
    addText(td, a[i]);   
    tr.appendChild(td);
  }
}

function addText(el, text)
{
  if(document.all)
    el.innerText = text;
  else
    el.textContent = text;
}


function createEcbItems(parent)
{
  var table = document.createElement('table');
  table.setAttribute("id","ECBItems");
  table.setAttribute("style","display:none");
  table.style.cssText = "display:none";
  table.appendChild(document.createElement('tbody'));
  parent.appendChild(table);
  return table;
}

function getEcbItemsOfById(n){
  return getEcbItemsOf(document.getElementById(n));
}

function getEcbItemsOf(t){
  var parentNode = t.parentNode;
  while (t != null && t.id != 'ECBItems')
      t = t.nextSibling;
  if(t == null)
    t = createEcbItems(parentNode);
  return t;
}

// Fix for SharePoint where only one ECB table is used, use the closest one
function GetEcbItems(ctx)
{
    var id = ctx.listName+"-"+ctx.view;
    var table = document.getElementById(id);
    if(table == null)
      table = GetScriptTag(ctx.listName);
        
    if(table != null)
    {
        var parent = table.parentNode;
        
        while(parent != null && parent.tagName != "TABLE")
            parent = parent.parentNode;

        return getEcbItemsOf(parent);    
    }
    else
        return document.getElementById("ECBItems");
}

function GetScriptTag(listid)
{
  var scriptTags = document.getElementsByTagName("script");
  var toLookFor = "ctx.listName = \""+listid+"\";";
  
  for(var i = 0; i<scriptTags.length; i++)
  {
    var text = scriptTags[i].innerHTML;
    if(text != null && text.indexOf(toLookFor) > 0)
        return scriptTags[i];
  }
  return null;
}